package edu.whut.mall.admin.shiro.auth;

import com.alibaba.fastjson.JSON;
import edu.whut.mall.common.api.ResponseMap;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.springframework.web.bind.annotation.RequestMethod;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Author: smq
 * Unit: D9lab
 * Description: 因为是前后端分离的项目，会产生跨域问题，自定义过滤器,解决跨域问题，options请求就是跨域请求，对跨域请求进行放行
 *              onAccessDenied是重写了shiro的权限放行判定
 * Date: 2021-06-12 14.52
 */
@Slf4j
public class MyAuthFilter extends FormAuthenticationFilter {


    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        return httpServletRequest.getMethod().equals(RequestMethod.OPTIONS.name());

    }

    @Override
    protected boolean onAccessDenied(ServletRequest servletRequest, ServletResponse servletResponse) throws Exception {
        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
        String token = httpServletRequest.getHeader("Authorization");
        Subject subject = SecurityUtils.getSubject();
        if (StringUtils.isBlank(token) || !subject.isAuthenticated()) {
            ResponseMap map = ResponseMap.getInstance();
            HttpServletResponse httpResponse = (HttpServletResponse) servletResponse;
            httpResponse.setHeader("Access-Control-Allow-Credentials", "true");
            httpResponse.setHeader("Access-Control-Allow-Origin", httpServletRequest.getHeader("Origin"));
            httpResponse.setCharacterEncoding("UTF-8");
            map.putFailure("权限校验失败，未登录或者未授权",0);
            String json = JSON.toJSONString(map);
            httpResponse.getWriter().print(json);
            return false;
        }
        log.info("=============前后端分离MyAuthFilter=================" + token);
        return true;
    }


}
